// api
import { chatList } from '@api/chat'
// stores
import { useGlobalStore } from '@stores'
// router
import router from '@router'
// api
import { chatSave } from '@api/chat'

export const useChat = async (id: number) => {
  const userStore = useGlobalStore().userStore
  const chatStore = useGlobalStore().chatStore
  // 初始化
  chatStore.init(id)
  // 请求会话列表
  const res = await chatList({
    userId: userStore.userInfo.userId + '',
    type: '3',
    functionType: id,
    pageSize: 20,
    page: chatStore.page
  })
  if (res.code != 0) return
  let chatId = ''
  if (res.data.length) {
    const newData = res.data.filter((item) => item.dateType === '1')
    const oldData = res.data.filter((item) => item.dateType === '2')
    //   存数据
    chatStore.menuList[0].list = newData
    chatStore.menuList[1].list = oldData
    chatId = res.data[0].id + ''
  } else {
    // 手动创建一条
    const res = await chatSave({
      userId: userStore.userInfo.userId,
      type: chatStore.menuId
    })
    if (res.code != 0) return
    // 存数据
    chatStore.menuList[0].list.push({
      id: res.data.chatId,
      userId: userStore.userInfo.userId,
      question: '智能对话',
      type: chatStore.menuId,
      assistantId: null,
      identity: null,
      occupation: null,
      workTime: null,
      technology: null,
      dateType: '1',
      created: '',
      updated: ''
    })
    chatId = res.data.chatId + ''
  }
  //   跳转到chat
  router.push({
    path: '/chat',
    query: {
      id: chatId
    }
  })
}
